<!DOCTYPE html>
<html lang="en">
<head>
    <title >ThreeJs限制模型拖动的范围</title >
    <meta charset="UTF-8">
    <!--引入three.js，这是使用three必须的js文件，此处引入的是外网提供的three文件，如果引入有问题可以到官网下载three文件后引入本地的theee.js文件-->
</head>
 
<body>
    <script type="importmap">
        {
            "imports": {
                "three": "../js/threejs/three.module.js",
                "three/addons/": "../js/threejs/jsm/"
            }
        }
    </script>
    <script type="module">
        import * as THREE from 'three';
        import { TrackballControls } from 'three/addons/controls/TrackballControls.js';
        import { DragControls } from 'three/addons/controls/DragControls.js';
        import { TransformControls } from 'three/addons/controls/TransformControls.js';
        import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
        import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
        import {OutlinePass} from 'three/addons/postprocessing/OutlinePass.js';
        import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
    var modelX = 0;//x轴位置
    var modelY = 0;//y轴位置
	
	var modelMinZ = -100; //z轴可拖动最小范围
	var modelMaxZ = 100;//z轴可拖动最大范围
	
    /**
     * 创建场景对象Scene
     */
    var scene = new THREE.Scene();
	
	const axesHelper = new THREE.AxesHelper( 100 );
    axesHelper.position.set(0,0,0)
    scene.add( axesHelper );

    
 
    /**
     * 相机设置
     */
    //窗口宽度
    var width = window.innerWidth;
    //窗口高度
    var height = window.innerHeight;
    //窗口宽高比
    var k = width / height;
    //三维场景显示范围控制系数，系数越大，显示的范围越大
    var s = 200;
    //创建相机对象
    var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
    //设置相机位置
    camera.position.set(200, 300, 200);
    //设置相机方向(指向的场景对象)
    camera.lookAt(scene.position);
 
    /**
     * 光源设置
     */
        //新建点光源(常用光源分为点光源和环境光，点光源的效果类似灯泡，环境光的效果类似白天的太阳光)
    var point = new THREE.PointLight(0xffffff);
    //设置点光源的位置
    point.position.set(400, 200, 300);
    //将点光源添加到场景中
    scene.add(point);
 
    /**
     * 创建网格模型，也就是3D模型
     */
    //创建一个立方体几何对象Geometry
    var geometry = new THREE.BoxGeometry(100, 100, 100);
    //给几何体创建材质，这里是改为蓝色，材质对象Material
    var material = new THREE.MeshLambertMaterial({
        color: 0xFF00ff
    });
    //网格模型对象Mesh
    var mesh = new THREE.Mesh(geometry, material);
    //网格模型添加到场景中，每个模型最终都要添加到场景中才会被渲染
	mesh.name = 'box'

    // 长方体作为EdgesGeometry参数创建一个新的几何体
	const edges = new THREE.EdgesGeometry(geometry);
	const edgesMaterial = new THREE.LineBasicMaterial({
	  color: 0xff0000,
	})
	const line = new THREE.LineSegments(edges, edgesMaterial);
    //方法二
    // const line1 = new THREE.BoxHelper(mesh, 0xff0000);
    // const line1 = new THREE.BoxHelper(mesh, 0xff0000);
    // scene.add(line1);

    mesh.add(line);
    scene.add(mesh);

    
	
    /**
     * 创建渲染器对象
     */
    //创建渲染器对象(渲染要等所有东西都加进去再渲染场景，创建和3D模型和光源没有先后顺序)
    var renderer = new THREE.WebGLRenderer();
    //设置渲染区域尺寸(设置的是整个屏幕的长度和宽度
    renderer.setSize(width, height);
    //设置渲染的背景色
    renderer.setClearColor(0xb9d3ff, 1);
    //body元素中插入canvas对象，也可以在页面中添加div，并加上id，通过id指定在某个div中渲染
    document.body.appendChild(renderer.domElement);
	
    initOutlinePass(scene,camera,renderer,mesh);
    
	//循环渲染
	function render() {
		//执行渲染操作   指定场景、相机作为参数
		renderer.render(scene, camera);
		// 使用 requestAnimationFrame 函数安排下一次渲染
		requestAnimationFrame(render);
		//修改正方体网格的x轴旋转角度
		//mesh.rotation.x += 0.02
	}

    //给正方体添加描边效果
    function initOutlinePass(hScene,hCamera,hRenderer,hMess){
      let renderScene = new RenderPass(hScene, hCamera);
      let outlinePass = new OutlinePass(
          new THREE.Vector2(window.innerWidth, window.innerHeight),
          hScene,
          hCamera,
          [hMess]
      );
      // 将此通道结果渲染到屏幕
      outlinePass.renderToScreen = true
      outlinePass.edgeGlow = 1 // 发光强度
      outlinePass.usePatternTexture = false // 是否使用纹理图案
      outlinePass.edgeThickness = 10 // 边缘浓度
      outlinePass.edgeStrength = 10 // 边缘的强度，值越高边框范围越大
      outlinePass.pulsePeriod = 2// 闪烁频率，值越大频率越低
      outlinePass.visibleEdgeColor.set('#ffff00') // 呼吸显示的颜色
      outlinePass.hiddenEdgeColor.set('#ff0000') // 不可见边缘的颜色
      // 将通道加入组合器
      var composer = new EffectComposer(hRenderer);
      composer.addPass(renderScene);
      composer.addPass(outlinePass);
      return composer;
    }
	//执行渲染
	render()
	
	/**
		添加鼠标拖动事件
	*/
	//需要创建一个数组，将需要拖动的对象放到数组中(mesh是上面创建的正方体)
	let objects = [];
	objects.push(mesh)
	var dragControls = new DragControls(objects, camera, renderer.domElement);
    //可视化变换控件对象
    var transformControl = new TransformControls( camera,renderer.domElement );
    //transformControl.setMode('translate');
    transformControl.setMode('rotate');


    
	
	//拖拽开始前记录此时模型位置
	dragControls.addEventListener( 'dragstart', function ( event ) {
		modelX = event.object.position.x
		modelY = event.object.position.y
		console.log("拖动前"+modelX+","+modelY)
	});
	
	//拖拽时重置x和y轴位置，并判断z轴是否在范围内，如果不在则设置回范围内的位置
	dragControls.addEventListener( 'drag', function ( event ) {
		// if(event.object.position.z > modelMaxZ){
		// 	event.object.position.z = modelMaxZ
		// }
		// if(event.object.position.z < modelMinZ){
		// 	event.object.position.z = modelMinZ
		// }
        // console.log('drag event-->',event);
		//event.object.position.set(modelX,modelY,event.object.position.z)
	});
	
	dragControls.addEventListener( 'dragend', function ( event ) {
		console.log("拖动后"+modelX+","+modelY)
        transformControl.detach();
	});

    //拖拽控件对象设置鼠标事件
    dragcontrols.addEventListener( 'hoveron', function ( event ) {
        //控件对象transformControl与选中的对象object绑定
        transformControl.attach( event.object );
    } )
 
    //https://blog.csdn.net/qq_33242956/article/details/123045412
    function createDragControls(objects) {
        // 初始化拖拽控件
        var dragControls = new DragControls(objects, camera, renderer.domElement);

        // 鼠标略过事件
        dragControls.addEventListener('hoveron', function (event) {
            console.log("createDragControls hoveron");
            // 让变换控件对象和选中的对象绑定
        });

        // 开始拖拽
        dragControls.addEventListener('dragstart', function (event) {
            console.log("createDragControls dragstart");
            orbitControls.enabled = false;
        });

        // 拖拽过程
        dragControls.addEventListener('drag', function (event) {
            console.log("createDragControls drag");
            dragControlsRender();
        });

        // 拖拽结束
        dragControls.addEventListener('dragend', function (event) {
            console.log("createDragControls dragend");
            orbitControls.enabled = true;
        });
    }
	//_plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) );
    // _plane.setFromNormalAndCoplanarPoint(new THREE.Vector3(0,0,1),new THREE.Vector3(0,0,1));
</script>
</body>
</html>